package com.youxin.logprocess.controller;


import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.youxin.busfoundation.config.MonitorBaseBean;
import com.youxin.busfoundation.config.MonitorZookeeperConfig;
import com.youxin.foundation.lang.BaseException;
import com.youxin.foundation.utils.thread.ScheduleThreadPool;
import com.youxin.foundation.zookeeper.ZookeeperConnector;
import com.youxin.logprocess.common.MonitorGlobalConfig;

/**
 * 监控Zookeeper
 * @author yingde.cao
 *
 */
public class MonitorZookeeperController extends BaseMonitorController{

	private static Logger logger = Logger.getLogger(MonitorZookeeperController.class);
	private static MonitorZookeeperController controller = new MonitorZookeeperController();
	
	private MonitorZookeeperConfig config;

	public MonitorZookeeperConfig getConfig() {
		return config;
	}

	public void setConfig(MonitorZookeeperConfig config) {
		this.config = config;
	}

	public static void initConfig(MonitorZookeeperConfig config) {
		controller.setConfig(config);
	}
	
	public static MonitorZookeeperController instance(){
		return controller;
	}
	
	@Override
	public MonitorBaseBean getMonitorBean() {
		return config;
	}
	
	/**
	 * 执行方法
	 */
	public void execute() {
		if(config==null)
		{
			throw new BaseException("请配置mointor.zookeeper的config");
		}
		if (config.getMonitor() != MonitorGlobalConfig.MONITOR_ON) {
			return;
		}
		
		for(String hosts:config.getServers())
		{
			ScheduleThreadPool.scheduleWithFixedDelay(new Runnable() {
				@Override
				public void run() {
					try {
						visitZookeeper(hosts);
					} catch (Exception e) {
						logger.error("执行任务异常:",e);
						adds(hosts, e);
					}
				}
			}, config.getInterval(), 1000);
		}		
	}
	
	
	private void visitZookeeper(String hosts){		
    	String[] urls=hosts.split(",",0);
		for(String url:urls)
		{
			ZookeeperConnector connector=null;
			try {
				url=StringUtils.trimToEmpty(url);
				if(url.length()==0){
					continue;
				}
				connector = new ZookeeperConnector();
				connector.connect(url);
			   if(!connector.isConnected())
			   {
				   add(url, "连接zookeeper:"+url+"失败");
			   }
			} catch (Exception e) {
				logger.error("连接Zookeeper发生错误:"+url, e);
				add(url, "连接zookeeper:"+url+"失败,"+e);
			}finally {
				try {
					connector.close();
				} catch (Exception e) {
					logger.error("关闭zookeeper发生错误:"+url, e);
				}
			}	
		}  	
	}

}
